import threading
import numpy
import libmedia_codec
import cv2


class Video_deal:
    connect = None
    video_decoder = libmedia_codec.H264Decoder()  # 获取解码器
    name = "LiveView"  # 定义视频窗口名称

    img = None  # 接收到的图片存储位置

    video_Switch = False
    video_update_thread = None

    show_Switch = False
    show_thread = None

    def __init__(self, connection=None, img_queue=None):
        self.img_queue = img_queue
        self.connect = connection
        self.show_thread = threading.Thread(target=self.video_show)

    def get_img(self):
        return self.img

    def show_on(self):
        self.show_Switch = True
        if self.show_thread is None:
            self.show_thread = threading.Thread(target=self.video_show)
        self.show_thread.start()

    def show_off(self):
        self.show_Switch = False

    def video_show(self):
        while self.show_Switch:
            if self.img is None:
                continue
            cv2.imshow(self.name, self.img)
            cv2.waitKey(1)

    # 对H264视频数据进行解码
    def _h264_decode(self, data):
        res_frame_list = []
        frames = self.video_decoder.decode(data)
        for frame_data in frames:
            (frame_raw, width, height, ls) = frame_data
            if frame_raw:
                frame_raw = numpy.fromstring(frame_raw, dtype=numpy.ubyte, count=len(frame_raw), sep='')
                frame = (frame_raw.reshape((height, width, 3)))
                res_frame_list.append(frame)
        return res_frame_list

    def renew_img(self):
        """
        获取一帧图片,并更新
        :return:
        """
        data = self.connect.rec_video()[0]
        video_message = b''
        video_message += data
        frames = self._h264_decode(video_message)
        for frame in frames:
            img = numpy.array(frame)
            if img.shape[0] > 0 and img.shape[1] > 0:
                self.img = img
                if self.img_queue is not None:
                    self.img_queue.put(img)
                return img
        return None

    def start(self):
        self.connect.send("streamon")  # 发送关闭视频流指令
        self.connect.rec_result()
        self.video_Switch = True
        if self.video_update_thread is None:
            self.video_update_thread = threading.Thread(target=self.img_update)
        self.video_update_thread.start()

    def img_update(self):
        while self.video_Switch:
            self.renew_img()
            # print(self.img)

    def stop(self):
        self.video_Switch = False
        self.connect.send("streamoff")  # 发送关闭视频流指令
        self.connect.rec_result()
